import { getAddressListApi, setDefaultAddressApi, editAddressApi, defaultAddressIdApi, getDefaultAddressApi, addAddressApi } from '@/api/address'

export default {
  namespaced: true,
  state () {
    return {
      addressList: [],
      defaultAddressId: 0,
      getDefaultAddress: {}
    }
  },
  mutations: {
    getAddressListMutation (state, result) {
      state.addressList = result
    },
    toggleCheckbox (state, id) {
      const address = state.addressList.find(item => { return item.address_id === id })
      address.isChecked = !address.isChecked
      address.isDefault = !address.isDefault
    },
    defaultAddressIdMutation (state, id) {
      state.defaultAddressId = id
    },
    getDefaultAddressMutation (state, detail) {
      state.getDefaultAddress = detail
    }
  },
  actions: {
    async getAddressListAction (context) {
      const result = await getAddressListApi()
      console.log(result)
      result.data.list.forEach((element, index) => {
        if (index === 0) {
          element.isChecked = true
          element.isDefault = true
        } else {
          element.isChecked = false
          element.isDefault = false
        }
      })
      context.commit('getAddressListMutation', result.data.list)
    },
    async setDefaultAddressAction (context, addressId) {
      const result = await setDefaultAddressApi(addressId)
      console.log(result)
    },
    async editAddressAction (context, obj) {
      const result = await editAddressApi(obj)
      console.log(result)
    },
    async defaultAddressIdAction (context) {
      const result = await defaultAddressIdApi()
      console.log(result)

      context.commit('defaultAddressIdMutation', result.data.defaultId)
    },
    async getDefaultAddressAction (context) {
      await context.dispatch('defaultAddressIdAction')
      const result = await getDefaultAddressApi(context.state.defaultAddressId)
      console.log(result)
      context.commit('getDefaultAddressMutation', result.data.detail)
    },
    async addAddressAction (context, obj) {
      const result = await addAddressApi(obj)
      console.log(result)
    }
  },
  getters: {}
}
